<?php

namespace addons\oil\controller;


use addons\sum\model\User;
use app\admin\model\oil\Fuel as FuelModel;
use app\common\library\Auth;
use think\Db;
use app\admin\model\oil\Store as StoreModel;
use addons\oil\model\Order as OrderModel;

class Store extends Base
{

    protected $noNeedLogin = ['index','detail'];
    protected $noNeedRight = ['*'];

    /**
     * 油站列表
     */
    public function index()
    {
        $params = $this->request->get();
        $latitude = $params['latitude'] ?? 0;
        $longitude = $params['longitude'] ?? 0;
        $per_page=$params['per_page'] ?? 10;
        $fuel_slug=$params['fuel_slug']??'';
        $radius=$params['radius']??'';// 搜索半径，单位：km
        $stores = StoreModel::show()->with(['fuel']);
        if($fuel_slug){
            $stores=$stores->whereExists(function ($query)use($fuel_slug){
                $store_table_name = (new StoreModel())->getQuery()->getTable();
                $fuel_table_name = (new FuelModel())->getQuery()->getTable();
                $query->table($fuel_table_name)->where('store_id=' . $store_table_name . '.id')->where(['type'=>$fuel_slug]);
            });
        }
        if ($latitude && $longitude) {
            $stores = $stores->field('*, ' . getDistanceBuilder($latitude, $longitude))->order('distance', 'asc');
            if($radius){
                // 计算经纬度范围
                $latRange = $radius / 110.574; // 每1度纬度大约为110.574km
                $lngRange = $radius / (111.320 * cos(deg2rad($latitude))); // 每1度经度在该纬度下的长度
                // 计算经纬度范围
                $minLat = $latitude - $latRange;
                $maxLat = $latitude + $latRange;
                $minLng = $longitude - $lngRange;
                $maxLng = $longitude + $lngRange;

                $stores=$stores->where('latitude', 'between', [$minLat, $maxLat])
                    ->where('longitude', 'between', [$minLng, $maxLng]);
            }
        }
        $stores=$stores->paginate($per_page);
        $stores->each(function ($store)use($fuel_slug){
            $fuel=FuelModel::where('store_id',$store['id'])->where('type',$fuel_slug)->find();
            $fuel_price=$fuel['price'];
            $amount=200;
            if($fuel_price>0){
                $discount_max=$fuel['discount_max']??0;
                $litre=$amount/$fuel_price; //升数
                $default_youhui=$discount_max*$litre;//最大优惠金额是每升的
            }else{
                $default_youhui=0;
            }
            $store['default_price']=$fuel_price;
            $store['default_amount']=$amount;
            $store['default_youhui']=number_format($default_youhui,2);
        });
        $this->success('油站列表',$stores);
    }
    /**
     * 油站详情
     */
    public function detail()
    {
        $params = $this->request->get();
        $latitude = $params['latitude'] ?? 0;
        $longitude = $params['longitude'] ?? 0;
        $id = $params['id'];
        if(!$id){
            $this->error('油站参数错误');
        }
        $store = StoreModel::show()->with('fuel')->where('id',$id);
        if ($latitude && $longitude) {
            $store = $store->field('*, ' . getDistanceBuilder($latitude, $longitude))->order('distance', 'asc');
        }
        $store=$store->find();
        $store=$store->toArray();
        foreach ($store['fuel'] as $fk=>&$fv){
            $fuel_price=$fv['price'];
            $amount=200;
            if($fuel_price>0){
                $discount_max=$fv['discount_max'];
                $litre=$amount/$fuel_price; //升数
                $default_youhui=$discount_max*$litre;//最大优惠金额是每升的
            }else{
                $default_youhui=0;
            }
            $fv['default_price']=$fuel_price;
            $fv['default_amount']=$amount;
            $fv['default_youhui']=number_format($default_youhui,2);
        }
        $this->success('油站详情',$store);
    }

    /**
     * 用户 油站信息
     * @return void
     */
    public function orderList()
    {
        $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile','store_id']);
        $user = $this->auth->getUserinfo();
        if(!$user['store_id']){
            $this->error('你没有权限');
        }
        $store=StoreModel::where('id',$user['store_id'])->field('id,name,status')->find();
        $keyword = $this->request->request('keyword');
        $order_q = new OrderModel();
        if($keyword){
            $order_q=$order_q->where('order_sn','like','%'.$keyword.'%');
        }
        $order_q=$order_q->where('store_id',$store['id'])->where('refund_status','in',['-1','0','1'])->payedorfinish();
        $orders = $order_q->order('id', 'desc')->paginate(10);
        $orders->each(function ($order){
            $order['order_sn_eight']=substr($order['order_sn'], -8);
            $order['order_sn_four']=substr($order['order_sn'], -4);
        });
        $return['user']=$user;
        $return['store']=$store;
        $return['orders']=$orders;
        $this->success('操作成功',$return);
    }

    public function orderDetail()
    {
        $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile','store_id']);
        $user = $this->auth->getUserinfo();
        if(!$user['store_id']){
            $this->error('你没有权限');
        }
        $return['user']=$user;
        $id = $this->request->request('id');
        if(!$id){
            $this->error('参数错误');
        }
        $store=StoreModel::where('id',$user['store_id'])->field('id,name,status')->find();
        $order_q = new OrderModel();
        $order_q=$order_q->where('id',$id)->where('store_id',$store['id'])->payedorfinish();
        $order = $order_q->find();
        $order['order_sn_eight']=substr($order['order_sn'], -8);
        $order['order_sn_four']=substr($order['order_sn'], -4);
        $return['order']=$order;
        $this->success('操作成功',$return);
    }
    public function doHexiao()
    {
        $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile','store_id']);
        $user = $this->auth->getUserinfo();
        if(!$user['store_id']){
            $this->error('你没有权限');
        }
        $id = $this->request->request('id');
        if(!$id){
            $this->error('参数错误');
        }
        $store=StoreModel::where('id',$user['store_id'])->field('id,name,status')->find();
        $order_q = new OrderModel();
        $order_q=$order_q->where('id',$id)->where('store_id',$store['id'])->payedorfinish();
        $order = $order_q->find();
        if(!$order){
            $this->error('没有该订单');
        }
        if($order['hexiao_status']==1){
            $this->error('该订单已核销');
        }
        if($order['aftersale_status']!=0){
            $this->error('该订单已申请售后');
        }
        if($order['refund_status']!=0){
            $this->error('该订单已申请退款');
        }

        $order->hexiao_status=1;
        $order->ext = json_encode($order->setExt($order, ['hexiao_time' => time()]));      // 完成时间
        $order->save();
        $type='store';
        \addons\oil\model\OrderAction::operAdd($order, $user, $type, '加油员核销订单','hexiao');
        //核销后操作
        $data = ['order' => $order];
        \think\Hook::listen('order_hexiao_after', $data);

        $return['order']=$order;
        $this->success('操作成功',$return);
    }


}
